import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getCartItems, addToCart, updateCartItem, removeCartItem, clearCart, getCartCount } from '@/api/cart'
import { useUserStore } from './user'
import { ElMessage } from 'element-plus'

export const useCartStore = defineStore('cart', () => {
  // 状态
  const cartItems = ref([])
  const loading = ref(false)

  // 计算属性
  const totalCount = computed(() => {
    return cartItems.value.reduce((total, item) => total + item.quantity, 0)
  })

  const totalPrice = computed(() => {
    return cartItems.value.reduce((total, item) => {
      return total + (item.price * item.quantity)
    }, 0)
  })

  // 方法
  const fetchCartItems = async () => {
    const userStore = useUserStore()
    if (!userStore.isLoggedIn) {
      cartItems.value = []
      return
    }

    try {
      loading.value = true
      const response = await getCartItems(userStore.userInfo?.id)
      if (response.data) {
        cartItems.value = response.data
      }
    } catch (error) {
      console.error('获取购物车失败:', error)
      ElMessage.error('获取购物车失败')
    } finally {
      loading.value = false
    }
  }

  const addItemToCart = async (productId, quantity = 1) => {
    const userStore = useUserStore()
    if (!userStore.isLoggedIn) {
      ElMessage.warning('请先登录')
      return false
    }

    try {
      const response = await addToCart(userStore.userInfo?.id, {
        productId,
        quantity
      })
      if (response.data) {
        await fetchCartItems() // 重新获取购物车数据
        ElMessage.success('添加成功')
        return true
      }
    } catch (error) {
      console.error('添加购物车失败:', error)
      ElMessage.error('添加失败')
      return false
    }
  }

  const updateItemQuantity = async (cartItemId, quantity) => {
    const userStore = useUserStore()
    if (!userStore.isLoggedIn) return false

    try {
      const response = await updateCartItem(userStore.userInfo?.id, cartItemId, quantity)
      if (response.data) {
        await fetchCartItems() // 重新获取购物车数据
        ElMessage.success('更新成功')
        return true
      }
    } catch (error) {
      console.error('更新数量失败:', error)
      ElMessage.error('更新失败')
      return false
    }
  }

  const removeItemFromCart = async (cartItemId) => {
    const userStore = useUserStore()
    if (!userStore.isLoggedIn) return false

    try {
      const response = await removeCartItem(userStore.userInfo?.id, cartItemId)
      if (response.data) {
        await fetchCartItems() // 重新获取购物车数据
        ElMessage.success('删除成功')
        return true
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
      return false
    }
  }

  const clearAllItems = async () => {
    const userStore = useUserStore()
    if (!userStore.isLoggedIn) return false

    try {
      const response = await clearCart(userStore.userInfo?.id)
      if (response.data) {
        cartItems.value = []
        ElMessage.success('清空成功')
        return true
      }
    } catch (error) {
      console.error('清空失败:', error)
      ElMessage.error('清空失败')
      return false
    }
  }

  const refreshCartCount = async () => {
    const userStore = useUserStore()
    if (!userStore.isLoggedIn) return 0

    try {
      const response = await getCartCount(userStore.userInfo?.id)
      return response.data || 0
    } catch (error) {
      console.error('获取购物车数量失败:', error)
      return 0
    }
  }

  return {
    cartItems,
    loading,
    totalCount,
    totalPrice,
    fetchCartItems,
    addItemToCart,
    updateItemQuantity,
    removeItemFromCart,
    clearAllItems,
    refreshCartCount
  }
}) 